package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.search.service.ApUserSearchService;
import com.heima.search.service.ArticleSearchService;
import com.heima.utils.common.DateUtils;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Autowired
    private ApUserSearchService apUserSearchService;

    /**
     * 文章搜索
     * @param dto
     * @return
     */
    @Override
    public ResponseResult search(UserSearchDto dto) {


        try {
            SearchRequest request = new SearchRequest("app_info_article");

            //设置查询条件---》我想买一个华为手机

            BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
            //第一个条件
            if(StringUtils.isBlank(dto.getSearchWords())){
                boolQuery.must(QueryBuilders.matchAllQuery());
            }else {
                boolQuery.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));

                //保存搜索历史
                ApUser user = AppThreadLocalUtil.getUser();
                if(user != null && dto.getFromIndex() == 0){
                    apUserSearchService.insert(user.getId(),dto.getSearchWords());
                }


            }

            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

            request.source().query(boolQuery);
            //分页
            request.source().from(0);
            request.source().size(dto.getPageSize());

            //按照时间倒序排序
            request.source().sort("publishTime", SortOrder.DESC);

            //设置高亮  三要素
            request.source().highlighter(new HighlightBuilder()
                    .field("title")
                    .preTags("<font style='color: red; font-size: inherit;'>")
                    .postTags("</font>"));

            //搜索
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析结果
            SearchHits searchHits = response.getHits();
            //总条数
            System.out.println(searchHits.getTotalHits().value);
            //获取具体文档数据
            SearchHit[] hits = searchHits.getHits();

            List<Map> resultList = new ArrayList<>();

            for (SearchHit hit : hits) {
                //文档数据
                Map map = JSON.parseObject(hit.getSourceAsString(), Map.class);

                //取出高亮结果数据
                Map<String, HighlightField> highlightFields = hit.getHighlightFields();
                if(highlightFields.size() > 0){
                    Text[] titles = highlightFields.get("title").fragments();
                    map.put("h_title",StringUtils.join(titles));
                }else {
                    map.put("h_title",map.get("title"));
                }
                resultList.add(map);
            }

            return ResponseResult.okResult(resultList);
        } catch (IOException e) {
            throw new RuntimeException("搜索失败");
        }

    }
}
